import axios from "axios"
import { baseUrl } from "./config.js"

//请求拦截器
axios.interceptors.request.use(
  config => {
    config.url = baseUrl + config.url

    config.headers = {
      'Content-Type': 'application/json',
      'x-token': token,
      'x-user-id': ID
    }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

//get请求方式
function get(config) {
  return new Promise((resolve, reject) => {
    axios({
      url: config.url,
      method: "get",
      params: config.data
    })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

//post请求方式
function post(config) {
  return new Promise((resolve, reject) => {
    axios({
      url: config.url,
      method: "post",
      data: config.data
    })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

function downloadPost(config) {
  return new Promise((resolve, reject) => {
    axios({
      url: config.url,
      method: "post",
      data: config.data,
      responseType: "blob"
    })
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        reject(err)
      })
  })
}

//put请求方式
function put(config) {
  return new Promise((resolve, reject) => {
    axios({
      url: config.url,
      method: "put",
      data: config.data
    })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

//deleteh请求方式
function deleted(config) {
  return new Promise((resolve, reject) => {
    axios({
      url: config.url,
      method: "delete",
      params: config.data
    })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

export default {
  get,
  post,
  downloadPost,
  put,
  deleted
}
